package cn.cdu.basics.redis;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;

@Configuration
public class RedissonConfig {
    
    private static final Logger logger = LoggerFactory.getLogger(RedissonConfig.class);
    private RedissonClient redisson;
    
    @Value("${spring.redis.host}")
    private String redisHost;
    
    @Value("${spring.redis.port}")
    private int redisPort;
    
    @Value("${spring.redis.password:}")
    private String redisPassword;
    
    @Value("${spring.redis.database:0}")
    private int redisDatabase;
    
    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        
        // Redis配置
        config.useSingleServer()
              .setAddress("redis://" + redisHost + ":" + redisPort)
              .setDatabase(redisDatabase)
              .setConnectionMinimumIdleSize(5)
              .setConnectionPoolSize(20)
              .setIdleConnectionTimeout(60000)
              .setConnectTimeout(10000)
              .setTimeout(3000);
        
        // 如果密码不为空，则设置密码
        if (redisPassword != null && !redisPassword.isEmpty()) {
            config.useSingleServer().setPassword(redisPassword);
        }
        
        redisson = Redisson.create(config);
        return redisson;
    }
    
    @PreDestroy
    public void destroy() {
        logger.info("Shutting down Redisson client...");
        try {
            if (redisson != null && !redisson.isShutdown()) {
                redisson.shutdown();
                logger.info("Redisson client shutdown complete");
            }
        } catch (Exception e) {
            logger.error("Error shutting down Redisson client", e);
        }
    }
} 